package com.zjw.spring_ai;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController("/chat")
public class ChatController {

    private final ChatClient chatClient;

    @Resource
    private OpenAiChatModel openAiChatModel;

    public ChatController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder.build();
    }

    @GetMapping("/call")
    public String chat(@RequestParam(value = "msg") String msg) {
         return this.chatClient.prompt()
                .user(msg)
                .call()
                .content();
    }

    @GetMapping(value = "/openAi/call/prompt")
    public Object callPrompt(@RequestParam(value = "msg") String msg) {
        ChatResponse chatResponse = openAiChatModel.call(new Prompt(msg));
        return chatResponse.getResult().getOutput().getText();
    }

    @GetMapping(value = "/openAi/call")
    public Object call(@RequestParam(value = "msg") String msg) {
            return openAiChatModel.call(msg);
    }

    /**
     * 调用OpenAI的接口
     *
     * @param msg 我们提的问题
     * @return
     */
    @GetMapping(value = "/option/chat")
    public Object fluxCall(@RequestParam(value = "msg") String msg) {
        //可选参数在配置文件中配置了，在代码中也配置了，那么以代码的配置为准，也就是代码的配置会覆盖掉配置文件中的配置
        Flux<ChatResponse> flux = openAiChatModel.stream(new Prompt(msg, OpenAiChatOptions.builder()
                //.withModel("gpt-4-32k") //gpt的版本，32k是参数量
                .temperature(0.4D) //温度越高，回答得比较有创新性，但是准确率会下降，温度越低，回答的准确率会更好
                .build()));

        flux.toStream().forEach(chatResponse -> System.out.println(chatResponse.getResult().getOutput().getText()));
        return flux.collectList(); //数据的序列，一序列的数据，一个一个的数据返回
    }
}
